<template>
  <div class="Home">
    <ul>
      <li v-for="(item, index) in wsData" :key="index">
        {{ item }}
      </li>
    </ul>
  </div>
</template>
<script>
import ReconnectingWebSocket from "reconnecting-websocket";
export default {
  name: "Home",
  data() {
    return {
      // 获取推送websocket
      ws: null,
      // 推送数据
      wsData: [],
    };
  },
  mounted() {
    // 获取推送数据
    this.getWebSocketData();
  },
  destroyed() {
    // 清空之前的匹配Ws连接容器
    this.stopWs(this.ws);
  },
  methods: {
    // 清空之前的匹配Ws连接容器
    stopWs(ws) {
      try {
        if (ws) {
          ws.close(1000);
          ws = {};
        }
      } catch (error) {
        console.warn(error);
      }
    },
    // 获取推送数据
    getWebSocketData() {
      // 清空之前的匹配Ws连接容器
      this.stopWs(this.ws);
      this.ws = new ReconnectingWebSocket("ws://192.168.1.11:8087/capture");
      this.ws.onmessage = (res) => {
        let data = JSON.parse(res.data);
        console.log(data);
        this.wsData.push(data);
      };
    },
  },
  watch: {
    // 推送数据不超过50
    wsData(value) {
      if (value.length > 50) {
        value.splice(value.length - 1, 1);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.Home {
}
</style>